package com.zorn.core.mybatis.interceptor;

import java.util.Map;
import java.util.Properties;

import org.apache.ibatis.cache.CacheKey;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Plugin;
import org.apache.ibatis.plugin.Signature;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;

import com.zorn.core.util.ParameterParser;

@Intercepts({ 
	@Signature(type = Executor.class, method = "query", args = { MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class }),
	@Signature(type = Executor.class, method = "query", args = { MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class,CacheKey.class, BoundSql.class }),
	@Signature(type = Executor.class, method = "update", args = { MappedStatement.class, Object.class })
})
public class ParameterParserInterceptor implements Interceptor {
	
	private final String complied = "";

	@SuppressWarnings("unchecked")
	@Override
	public Object intercept(Invocation invocation) throws Throwable {
		Object param = invocation.getArgs()[1];

		if (param instanceof Map<?, ?> && !((Map<?, ?>) param).containsKey("$$complied")) {
			Map<String, Object> compiled = ParameterParser.parse((Map<String, Object>) param);
			compiled.put("$$complied", true);
			invocation.getArgs()[1] = compiled;
		}
		return invocation.proceed();
	}

	@Override
	public Object plugin(Object target) {
		return Plugin.wrap(target, this);
	}

	@Override
	public void setProperties(Properties properties) {
	}

}
